#include <cmath>
#include <cstring>

void merge_prob(float *result, float *stats, float *logmarginal,
                float *rectmarginal, int NR_cate, int NR_cond)
{
    float *Ptic = new float[NR_cond * NR_cate];
    float *sumP = new float[NR_cond];
    memset(sumP, 0, sizeof(float) * NR_cond);
    memcpy(result, logmarginal, sizeof(float) * NR_cate);
    for (int c = 0; c < NR_cate; ++c)
    {
        for (int i = 0; i < NR_cond; ++i)
        {
            Ptic[i * NR_cate + c] =
                log(stats[i * NR_cate + c]) - logmarginal[c];
        }
    }
    //the above calculated P(dk|o=omegai)/\prod_k=1^KP(dk)
    for (int i = 0; i < NR_cond; ++i)
    {
        for (int c = 0; c < NR_cate; ++c)
        {
            result[c] += Ptic[i * NR_cate + c];
        }
    }
    for (int c = 0; c < NR_cate; ++c)
    {
        result[c] += rectmarginal[c];
    }
    float total = 0;
    for (int c = 0; c < NR_cate; ++c)
    {
        total += exp(result[c]);
    }
    float total_2 = 0;
    for (int c = 0; c < NR_cate; ++c)
    {
        result[c] = (exp(result[c])) / total;
        total_2 += result[c];
    }
    for (int c = 0; c < NR_cate; ++c)
    {
        result[c] = (result[c] + 0.001) / (total_2 + NR_cate * 0.001);
    }
    delete[]Ptic;
    delete[]sumP;
    return;
}
